<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchInput" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="应用名称" value="1"></el-option>
              <el-option label="内部版本" value="2"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- table -->
    <el-table stripe style="width: 100%" :data="searchTable" :key="key" border fit highlight-current-row ref="tableDataRef">
      <!-- <el-table-column v-if="colData[0].istrue" min-width="40" align="center" prop="id" label="ID"></el-table-column> -->
      <el-table-column v-if="colData[0].istrue" min-width="120" align="center" prop="username" label="归属"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="120" align="center" prop="app_name" label="应用名"></el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="170" align="center" prop="app_package" label="应用包名"></el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="130" align="center" prop="app_version_name" label="版本名称"></el-table-column>
      <el-table-column v-if="colData[4].istrue" min-width="130" align="center" prop="app_version_code" label="版本代码"></el-table-column>
      <el-table-column v-if="colData[5].istrue" min-width="230" align="center" prop="app_url" label="下载地址">
        <template slot-scope="scope">
          <div class="flex flex_cen">
            <input type="text" class="site_inputs" :value="scope.row.app_url" />
            <i class="el-icon-share download"> <a target="_blank" :href="scope.row.app_url"></a> </i>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[6].istrue" min-width="180" align="center" prop="remark" label="更新描述"></el-table-column>
      <el-table-column v-if="colData[7].istrue" min-width="80" align="center" prop="app_size" label="应用大小">
        <template slot-scope="scope">
          {{scope.row.app_size | zhDate}}
        </template>
      </el-table-column>
      <el-table-column v-if="colData[8].istrue" min-width="140" align="center" prop="create_time" label="创建时间">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column v-if="colData[9].istrue" min-width="130" align="center" prop="type" label="部署方式">
        <template slot-scope="scope"> {{scope.row.type == 1 ? 'SN部署' : '用户部署'}} </template>
      </el-table-column>
      <el-table-column v-if="colData[10].istrue" min-width="130" align="center" prop="sn_values" label="SN码"></el-table-column>
      <el-table-column v-if="colData[11].istrue" min-width="130" align="center" prop="batch_username" label="批次用户名"></el-table-column>
      <el-table-column v-if="colData[12].istrue" min-width="130" align="center" prop="batch" label="批次名称"></el-table-column>
      <el-table-column label="操作" min-width="100" align="center">
        <template slot-scope="scope">
          <el-button size="mini" round @click="appUpdateDelData(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :page-sizes="[10, 50, 100, 200]" :current-page.sync="listQuery.startSize" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
    </div>
    <!-- 添加 -->
    <el-dialog title="灰度更新" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
      <el-form :model="addForm" ref="ruleForm" :rules="rules" class="diolog_adapt">
        <el-form-item label="应用文件:" label-width="100px" class="snElsx" prop="address">
          <div class="addPut">
            <el-input autocomplete="off" disabled placeholder="请点击上传，上传apk件" style="flex:1" v-model="addForm.appUrl"></el-input>
            <!-- <el-upload class="upload-demo dlePut" style="top:0;right:10px" :action="`${uploadLink}api/apkAdmin`" accept=".APK" :data="pdfData" :show-file-list="false" name="apk" :on-progress="beforeAvatarUpload" :on-success="handleSuccess">
              <el-button round size="mini">上传{{videoFlag ? '' : videoUploadPercent + '%'}}</el-button>
            </el-upload> -->
            <el-upload class="upload-demo dlePut apkBtn" action="#" id="file" :auto-upload="false" :show-file-list="false" :on-change="apkFile">
              <el-button class="" round size="mini">上传{{videoFlag ? '' : goodsData + '%'}}</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="名称:" label-width="100px" prop="appName">
          <el-input v-model="addForm.appName" class="add_select" placeholder="请输入名称" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="应用包名:" label-width="100px" prop="appPackage">
          <el-input v-model="addForm.appPackage" class="add_select" placeholder="请输入应用包名"></el-input>
        </el-form-item>
        <el-form-item label="版本号:" label-width="100px" prop="versionName">
          <el-input v-model="addForm.versionName" class="add_select" placeholder="请输入版本号" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="内部版本号:" label-width="100px" prop="versionCode">
          <el-input v-model.number="addForm.versionCode" class="add_select" placeholder="请输入内部版本号" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="更新描述:" label-width="100px" prop="remark">
          <el-input maxlength="100" show-word-limit autocomplete="off" placeholder="请输入更新描述" type="textarea" class="add_select" v-model="addForm.remark" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="部署方式:" label-width="100px" prop="type">
          <el-radio-group v-model.number="addForm.type" @change="deployChange">
            <el-radio :label="1">SN部署</el-radio>
            <el-radio :label="0">用户部署</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="SN:" label-width="100px" prop="sn" v-if="deployShow">
          <el-select class="selectStyle" v-model="addForm.sn" remote multiple allow-create default-first-option popper-class="selectPopper" filterable :popper-append-to-body="false" size="small" placeholder="请输入SN码,用回车添加"></el-select>
        </el-form-item>
        <div v-else>
          <el-form-item label="用户名:" label-width="100px" prop="username">
            <el-select v-model="addForm.username" placeholder="请选择用户" class="add_select" @change="infoChange">
              <el-option v-for="item in optionInfo" :key="item.username" :label="item.username" :value="item.username"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="批次:" label-width="100px" prop="batch">
            <el-select v-model="addForm.batch" placeholder="请先选择用户名" class="add_select" remote multiple allow-create default-first-option>
              <el-option v-for="item in optionBatch" :key="item.id" :label="item.batch" :value="item.id.toString()"></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="dialogFormVisible = false" size="mini" round>取 消</el-button>
        <Debounce>
          <el-button v-if="editSubjects" type="primary" @click.native="getaddAppTest('ruleForm')" size="mini" round>确 定</el-button>
        </Debounce>
      </div>
    </el-dialog>
    <!-- 删除弹窗 -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />

  </div>
</template>

<script>
import UploadExcelComponent from "@/components/UploadExcelSn/index.vue";
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { appUpdateListData, uploadExecl, addAppUpdateData, appUpdateDelData, queryUsername, queryUsernameBatch, addAppTest, queryAppTest, deleteAppTest } from "@/api/appUpdate";
import deleteDialog from "@/components/deleteDialog";
import { ossupload, ossImage } from '@/utils/ossUpload.js'
import readMachine from 'app-info-parser'
import BMF from 'browser-md5-file'
import jszip from 'jszip'
import { mapState } from 'vuex'
export default {
  components: { UploadExcelComponent, dynamicTable, deleteDialog },
  data() {
    return {
      checkboxVal: ["归属", "应用名", "应用包名", "版本名称", "版本代码", "下载地址", "更新描述", "应用大小", "创建时间", "部署方式", "SN码", "批次用户名", "批次名称"],
      key: 1,
      colData: [], //动态控制table
      total: 0,
      searchTable: [],
      searchInput: '',
      select: "", //搜索条件
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制 
      editSubjects: true,
      //浏览器专题id
      subjectId: 0,
      addForm: {
        sn: '',
        type: 1,
        appPackage: '',
        appSize: '',
        appName: '',
        versionName: '',
        versionCode: '',
        appUrl: '',
        appMd5: '',
        batch: '',
        remark: '',
        username: ''
      },
      deployShow: true,
      optionInfo: [],//用户名
      optionBatch: [],
      rules: {
        appName: [{ required: true, message: "请输入名称", trigger: "blur" }],
        appPackage: [{ required: true, message: "请输入应用包名", trigger: "blur" }],
        versionName: [{ required: true, message: "请输入版本号", trigger: "blur" }],
        versionCode: [{ required: true, message: "请输入内部版本号", trigger: "blur"}],
        appUrl: [{ required: true, message: "请上传应用文件", trigger: "blur" }],
        remark: [{ required: true, message: "请输入更新描述", trigger: "blur" }],
        sn: [{ required: true, message: "请上传文件", trigger: "blur" }],
      },
      //进度条
      videoUploadPercent: 0,
      videoFlag: true,
      pdfData: { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip") },
      listQuery: { startSize: 1, pageSize: 10, appName: undefined, versionCode: undefined },
      //删除弹窗
      deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
      uploadLink: process.env.VUE_APP_BASE_API
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
    this.getqueryAppTest()
    this.getqueryUsername()
    this.pdfData.userId = localStorage.getItem("ID")
  },
  computed: {
    ...mapState({//获取上传滚动条
      goodsData: state => state.user.progress
    })
  },
  methods: {
    //获取md5
    apkMd5(file) {
      const bmf = new BMF()
      bmf.md5(file, (err, md5) => {//获取文件MD5
        this.addForm.appMd5 = md5
        console.log('md5 string:', err, md5)
      });
    },
    apkFile(event) {
      var filePath = event.name //文件名
      var index = filePath.lastIndexOf(".");
      var ext = filePath.substr(index + 1);
      this.addForm.appSize = event.size
      var supportFileTypes = ['ipa', 'apk', 'xapk'];
      var splits = (event.name || event).split('.');
      var fileType = splits[splits.length - 1].toLowerCase();
      if (!supportFileTypes.includes(fileType)) return this.$message.error('请上传正确的文件格式')
      const parser = new readMachine(event.raw)
      this.videoFlag = false;
      this.apkMd5(event.raw)//获取文件MD5
      ossupload(event.raw, filePath, true, event.size).then(res => {
        this.videoFlag = true;
        this.addForm.appUrl = res
        this.$store.commit('user/SET_PROGRESS', 0)
        //this.ossApk(event.raw, filePath)
        //文件类型
        if (ext == 'xapk') {//xapk
          this.getXapkInfo(parser);
        } else {
          parser.parse().then(res => {//apk
            this.addForm.appPackage = res.package;
            this.addForm.versionName = res.versionName;
            this.addForm.versionCode = res.versionCode;
            this.addForm.appName = (res.application.label).constructor == Array ? res.application.label[0] : res.application.label;
          }).catch(err => {
            this.$message.error('无法识别文件格式, 请重新上传')
          })
        }
      }).catch(err => {
        this.videoFlag = true;
        this.$store.commit('user/SET_PROGRESS', 0)
        err.code == 10086 ? this.$message(err.msg) : ''
        //上传oss失败关闭弹窗
        this.addFormVisible = false
      })
    },
    //获取xapk信息
    getXapkInfo(parser, type) {
      const xapk = parser
      let file = xapk.file;
      let blob = new Blob([file]);
      this.addFormVisible = type ? false : true
      jszip.loadAsync(blob, { optimizedBinaryString: true }).then(res => {
        for (let key in res.files) {
          //判断是否是目录
          if (!res.files[key].dir) {
            //找到我们压缩包所需要的json文件
            if (/\.(json)$/.test(res.files[key].name)) {
              res.file(res.files[key].name).async('string').then(item => {
                //得到我们需要的JSON文件内容
                let infocontent = JSON.parse(item);
                this.addForm.appPackage = infocontent.package_name;
                this.addForm.versionName = infocontent.version_name;
                this.addForm.versionCode = infocontent.version_code;;
                this.addForm.appName = infocontent.name;
              })
            }
          }
        }
      }).catch(err => {
        console.log('zpi失败', err)
      });
    },
    //删除
    appUpdateDelData(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    //删除按钮事件
    deleteEvents() {
      let params = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), id: this.deleteDialogs.deleteId }
      deleteAppTest(params).then(res => {
        this.$message.success(res.msg)
        this.getqueryAppTest()
      })
    },
    //部署方式change事件
    deployChange(val) {
      if (val == 0) {
        this.deployShow = false
      } else {
        this.deployShow = true
      }
    },
    //选取用户名change事件
    infoChange(val) {
      this.addForm.batch = ''
      this.getqueryUsernameBatch(val)
    },
    //获取所有用户
    getqueryUsername() {
      queryUsername().then(res => {
        this.optionInfo = res.data
      }).catch(err => {
        this.optionInfo = []
      })
    },
    //根据用户获取批次
    getqueryUsernameBatch(name) {
      queryUsernameBatch({ username: name }).then(res => {
        this.optionBatch = res.data
      }).catch(err => {
        this.optionBatch = []
      })
    },
    //添加
    getaddAppTest(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.userId = localStorage.getItem("ID")
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.sn != '' ? addForm.sn = this.addForm.sn.toString() : ''
          addForm.batch != '' ? addForm.batch = this.addForm.batch.toString() : ''
          addAppTest(addForm).then(res => {
            this.$message.success('添加成功')
            this.getqueryAppTest()
            this.dialogFormVisible = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    btnaddBrand() {
      this.editSubjects = true
      this.dialogFormVisible = true
    },
    beforeAvatarUpload() {
      this.apkUnplate = false;//将添加和上传的按钮分开
      this.videoFlag = false;
      if (Math.floor(event.percent) <= 99) {
        this.videoUploadPercent = Math.floor(event.percent)
      }
    },
    handleSuccess(res) {
      if (res.code == 200) {
        this.videoUploadPercent = 100;
        setTimeout(() => {
          this.videoUploadPercent = 0;
          this.videoFlag = true
          console.log('上次的apk', res)
          this.addForm.appUrl = res.data.filePath
          this.addForm.appName = res.data.appName
          this.addForm.appPackage = res.data.bg
          this.addForm.versionName = res.data.versionName
          this.addForm.versionCode = res.data.versionCode
          this.addForm.appMd5 = res.data.md5
          this.addForm.appSize = res.data.size
        }, 500)
      } else {
        this.$message.error(res.msg)
        this.videoUploadPercent = 0;
        this.videoFlag = true
      }
    },
    //SN码导入上传
    beforeUpload(file) {
      var fd = new FormData()
      fd.append('file', file)
      uploadExecl(fd).then(res => {
        this.addForm.sn = res.data.img_path
      })

    },
    getqueryAppTest() {
      queryAppTest(this.listQuery).then(res => {
        this.searchTable = res.data
        this.total = res.total
        console.log('------参数', res)
      }).catch(err => {
        this.searchTable = []
        this.total = 0
      })
    },
    //搜索,1:网址，2:类型
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.appName = this.searchInput
          this.getqueryAppTest();
          break;
        case '2':
          this.listQuery.versionCode = this.searchInput
          this.getqueryAppTest();
          break;
      }
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 10, appName: undefined, versionCode: undefined }
      this.getqueryAppTest()
    },
    //分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getqueryAppTest()
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getqueryAppTest()
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.addForm = {
          sn: '',
          type: 1,
          appPackage: '',
          appSize: '',
          appName: '',
          versionName: '',
          versionCode: '',
          appUrl: '',
          appMd5: '',
          batch: '',
          remark: '',
          username: ''
        }
      })
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    }
  }
}
</script>

<style scoped>
.selectStyle {
  width: 89%;
}
</style>